package com.example.demo.controller;

import com.example.demo.common.ResponseData;
import com.example.demo.domain.FileInfo.FileInfo;
import com.example.demo.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    IFileService fileService;

    private String UPLOADED_FOLDER = "D:\\file\\";
    @RequestMapping("/upload")
    public ResponseData<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
        //int i=1/0;
        if(file.isEmpty()){
            return ResponseData.fail("上传文件不能为空");
        }
        try {
            byte[] bytes = file.getBytes();
            String fileName = file.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf("."));
            String fileId = UUID.randomUUID().toString();
            String filePath = UPLOADED_FOLDER + fileId + extName;
            Path path = Paths.get(filePath);
            Files.write(path, bytes);
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFileId(fileId);
            fileInfo.setFileName(fileName);
            fileInfo.setFilePath(filePath);
            fileService.upload(fileInfo);
            return ResponseData.ok(filePath,"上传成功");
        }catch (IOException e){
            return ResponseData.fail("上传失败");
        }
    }

    @GetMapping("/download")
    public void download(@RequestParam("fileId") String fileId, HttpServletResponse response) throws IOException{
        FileInfo fileInfo = fileService.getFile(fileId);
        InputStream inputStream = new FileInputStream(fileInfo.getFilePath());
        response.reset();
        response.setContentType("application/octet-stream");
        String fileName = fileInfo.getFileName();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
    }
}
